package com.free.solon.common.xss;

import cn.hutool.core.util.StrUtil;
import com.free.solon.common.utils.XssUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

import java.util.Map;

/**
 * @Author: hao.ding@insentek.com
 * @Date: 2024/5/21 10:07
 */
@Slf4j
@Component
public class XssRouterInterceptor implements RouterInterceptor {

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        if (mainHandler != null) {
            //请求头
            for (Map.Entry<String, String> kv : ctx.headerMap().entrySet()) {
                //处理Val
                kv.setValue(cleanXss(kv.getValue()));
            }

            //请求参数
            for (Map.Entry<String, String> kv : ctx.paramMap().entrySet()) {
                //处理val
                kv.setValue(cleanXss(kv.getValue()));
            }

            //请求主体
            if (ctx.contentType() != null && ctx.contentType().contains("json")) {
                //处理vaL
                ctx.bodyNew(cleanXss(ctx.body()));
            }
        }

        chain.doIntercept(ctx, mainHandler);
    }

    private String cleanXss(String input) {
        if(StrUtil.isBlankOrUndefined(input)){
            return input;
        }

        input = XssUtil.removeEvent(input);
        input = XssUtil.removeScript(input);
        input = XssUtil.removeEval(input);
        input = XssUtil.swapJavascript(input);
        input = XssUtil.swapVbscript(input);
        input = XssUtil.swapLivescript(input);
        input = XssUtil.encode(input);

        return input;
    }
}
